package com.asiainfo.dao;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisHelper {

	private static final String defaultEnvironment = "defalut";
	private static final String defaultConfigXml = "mybatis-config.xml";
	private static final Map<String, SqlSessionFactory> sessionFactoryMap = new HashMap<String, SqlSessionFactory>();
	private static final Map<String, MapperScan> mapperScanMap = new HashMap<String, MapperScan>();

	public static SqlSessionFactory getSqlSessionFactory() {
		return getSqlSessionFactory(defaultEnvironment);
	}

	public static SqlSessionFactory getSqlSessionFactory(String environment) {
		environment = StringUtils.defaultString(environment, defaultEnvironment);
		SqlSessionFactory sessionFactory = sessionFactoryMap.get(environment);
		if (sessionFactory != null)
			return sessionFactory;
		Reader reader = null;
		try {
			synchronized (sessionFactoryMap) {
				reader = Resources.getResourceAsReader(defaultConfigXml);
				StringUtils.defaultString(environment, defaultEnvironment);
				sessionFactory = new SqlSessionFactoryBuilder().build(reader, environment);
				sessionFactoryMap.put(environment, sessionFactory);
				MapperScan mapperScan = new MapperScan();
				mapperScan.loadMappers(sessionFactory.getConfiguration());
				mapperScanMap.put(environment, mapperScan);
				return sessionFactory;
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static SqlSession getSqlSession() {
		return getSqlSessionFactory().openSession();
	}

	public static SqlSession getSqlSession(String environment) {
		return getSqlSessionFactory(environment).openSession();
	}

	public static MapperScan getMapperScan(String environment) {
		return mapperScanMap.get(environment);
	}

	public static MapperScan getMapperScan() {
		return mapperScanMap.get(defaultEnvironment);
	}

	public synchronized static void reset() {
		sessionFactoryMap.clear();
		mapperScanMap.clear();
	}
	
}